package com.docchatlink.iflytek2.client;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.docchatlink.dto.ResponseMsg;
import com.docchatlink.dto.v2.*;
import com.docchatlink.iflytek2.config.IflytekConfig2;
import com.docchatlink.iflytek2.vo.*;
import com.docchatlink.util.ApiAuthUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 连接星火知识库V2.0
 * </p>
 *
 * @author Mr.piggy
 * @since 2024/6/24
 */
@Service
@Slf4j
public class IflytekDocV2Client {

    @Resource
    private IflytekConfig2 iflytekConfig2;

    public String initChat() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
    /**
     * 文档管理模块相关接口
     */
    /**
     * 文档上传
     * 上传知识库文档数据，目前支持word、pdf、md、txt格式，单文件大小不超过20MB，不超过100W字符。
     * POST，multipart/form-data
     *
     * @param param FileUploadParam 文件上传参数
     * @return UploadV2Resp
     */
    public ResponseMsg fileUpload(MultipartFile file, FileUploadParam param) throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .readTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .connectTimeout(20, TimeUnit.SECONDS)
                .build();

        RequestBody fileBody = RequestBody.Companion.create(file.getBytes(), MediaType.parse("multipart/form-data"));

        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);
        builder.addFormDataPart("file", file.getOriginalFilename(), fileBody);
        builder.addFormDataPart("fileType", ObjectUtil.isNotEmpty(param.getFileType()) ? param.getFileType() : "wiki");
        builder.addFormDataPart("parseType", ObjectUtil.isNotEmpty(param.getParseType()) ? param.getParseType() : "AUTO");
        RequestBody body = builder.build();
        long ts = System.currentTimeMillis() / 1000;

        String signature = ApiAuthUtil.getSignature(iflytekConfig2.getAppId(), iflytekConfig2.getApiSecret(), ts);
        Request request = new Request.Builder()
                .url(iflytekConfig2.getFileUploadUri())
                .post(body)
                .addHeader("appId", iflytekConfig2.getAppId())
                .addHeader("timestamp", String.valueOf(ts))
                .addHeader("signature", signature)
                .build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            if (Objects.equals(response.code(), 200)) {
                String respBody = response.body().string();
                log.info("respBody: {}", respBody);
                JSONObject respJson = JSON.parseObject(respBody);
                return ResponseMsg.success(JSONUtil.toBean(respBody, UploadV2Resp.class), (String) respJson.get("desc"), (String) respJson.get("sid"));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    /**
     * 文档切分
     * 根据切分符对文档进行切分，上传文件之后会做一次切分，若切分效果不满意可调用此方法重新切分。
     * POST，application/json
     *
     * @param fileSplitParam FileSplitParam
     * @return
     */
    public ResponseMsg fileSplit(FileSplitParam fileSplitParam) {
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .readTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .connectTimeout(20, TimeUnit.SECONDS)
                .build();

        long ts = System.currentTimeMillis() / 1000;

        String json = JSONUtil.toJsonStr(fileSplitParam);
        RequestBody requestBody = RequestBody.Companion.create(MediaType.parse("application/json"), json);
        String signature = ApiAuthUtil.getSignature(iflytekConfig2.getAppId(), iflytekConfig2.getApiSecret(), ts);
        // 创建请求
        Request request = new Request.Builder()
                .url(iflytekConfig2.getFileSplitUri())
                .post(requestBody)
                .addHeader("appId", iflytekConfig2.getAppId())
                .addHeader("timestamp", String.valueOf(ts))
                .addHeader("signature", signature)
                .build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            if (Objects.equals(response.code(), 200)) {
                String respBody = response.body().string();
                log.info("respBody: {}", respBody);
                JSONObject respJson = JSON.parseObject(respBody);
                return ResponseMsg.success(respJson.get("data"), (String) respJson.get("desc"), (String) respJson.get("sid"));
            }
        } catch (IOException e) {
            log.error("调用异常", e);
            throw new RuntimeException("调用异常", e);
        }
        return null;
    }

    /**
     * 文档向量化
     * 对文档切分的文本块进行向量化操作（embedding），对于文件状态处于splited的文件，可以调用该方法进行向量处理。只有向量化之后的文件才可以发起问答。
     * POST，application/form-data
     *
     * @param fileIds 上传的文件id列表，多个文档id用英文逗号分割
     * @return ResponseMsg
     */
    public ResponseMsg fileEmbedding(String fileIds) {
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .readTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .connectTimeout(20, TimeUnit.SECONDS)
                .build();

        long ts = System.currentTimeMillis() / 1000;
        // 创建一个FormBody.Builder对象
        FormBody.Builder formBuilder = new FormBody.Builder();

        // 添加POST参数
        formBuilder.add("fileIds", fileIds);

        // 创建一个RequestBody对象，用于包装表单数据
        RequestBody requestBody = formBuilder.build();

        String signature = ApiAuthUtil.getSignature(iflytekConfig2.getAppId(), iflytekConfig2.getApiSecret(), ts);
        // 创建请求
        Request request = new Request.Builder()
                .url(iflytekConfig2.getFileEmbeddingUri())
                .post(requestBody)
                .addHeader("appId", iflytekConfig2.getAppId())
                .addHeader("timestamp", String.valueOf(ts))
                .addHeader("signature", signature)
                .build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            if (Objects.equals(response.code(), 200)) {
                String respBody = response.body().string();
                log.info("respBody: {}", respBody);
                JSONObject respJson = JSON.parseObject(respBody);
                return ResponseMsg.success(respJson.get("data"), (String) respJson.get("desc"), (String) respJson.get("sid"));
            }
        } catch (IOException e) {
            log.error("调用异常", e);
            throw new RuntimeException("调用异常", e);
        }
        return null;
    }

    /**
     * 文档状态查询
     * 查询文件状态，文件从上传到可问答，
     * 经历的状态如下（按顺序）：uploaded-已上传，texted-已文本化，ocring-对文档OCR识别中，spliting-切分中，splited-文本已切分，vectoring-向量中，vectored-已向量化（该状态时可问答），failed-失败。
     * GET，application/form-data
     *
     * @param fileIds 上传的文件id列表，多个文档id用英文逗号分割
     * @return StatusResp
     */
    public ResponseMsg fileStatus(String fileIds) {
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .readTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .connectTimeout(20, TimeUnit.SECONDS)
                .build();

        long ts = System.currentTimeMillis() / 1000;

        String requestUrl = iflytekConfig2.getFileStatusUri() + "?fileIds=" + fileIds;
        log.info("requestUrl:{}", requestUrl);
        String signature = ApiAuthUtil.getSignature(iflytekConfig2.getAppId(), iflytekConfig2.getApiSecret(), ts);
        // 创建请求
        Request request = new Request.Builder()
                .url(requestUrl)
                .get()
                .addHeader("appId", iflytekConfig2.getAppId())
                .addHeader("timestamp", String.valueOf(ts))
                .addHeader("signature", signature)
                .build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            if (Objects.equals(response.code(), 200)) {
                String respBody = response.body().string();
                log.info("respBody:{}", respBody);
                JSONObject respJson = JSON.parseObject(respBody);
                return ResponseMsg.success(JSONUtil.toBean(respBody, StatusResp.class), (String) respJson.get("desc"), (String) respJson.get("sid"));
            }
        } catch (IOException e) {
            log.error("调用异常", e);
            throw new RuntimeException("调用异常", e);
        }
        return null;
    }

    /**
     * 文档内容相似度检索
     * 根据输入的文本，检索拆分后的相关原始文本块。
     * POST，application/json
     *
     * @param param VectorSearchParam
     * @return VectorSearchResp
     */
    public ResponseMsg vectorSearch(VectorSearchParam param) {
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .readTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .connectTimeout(20, TimeUnit.SECONDS)
                .build();

        long ts = System.currentTimeMillis() / 1000;

        String json = JSONUtil.toJsonStr(param);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), json);

        String signature = ApiAuthUtil.getSignature(iflytekConfig2.getAppId(), iflytekConfig2.getApiSecret(), ts);
        // 创建请求
        Request request = new Request.Builder()
                .url(iflytekConfig2.getVectorSearchUri())
                .post(requestBody)
                .addHeader("appId", iflytekConfig2.getAppId())
                .addHeader("timestamp", String.valueOf(ts))
                .addHeader("signature", signature)
                .build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            if (Objects.equals(response.code(), 200)) {
                String respBody = response.body().string();
                log.info("respBody: {}", respBody);
                JSONObject respJson = JSONObject.parseObject(respBody);
                return ResponseMsg.success(JSONUtil.toBean(respBody, VectorSearchResp.class), (String) respJson.get("desc"), (String) respJson.get("sid"));
            }
        } catch (IOException e) {
            log.error("调用异常", e);
            throw new RuntimeException("调用异常", e);
        }
        return null;
    }

    /**
     * 文档分块内容获取
     * 获取文件分块内容
     * GET，application/form-data
     *
     * @param fileId 上传的文件id
     * @return ChunksResp
     */
    public ResponseMsg fileChunks(String fileId) {
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .readTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .connectTimeout(20, TimeUnit.SECONDS)
                .build();

        long ts = System.currentTimeMillis() / 1000;

        String signature = ApiAuthUtil.getSignature(iflytekConfig2.getAppId(), iflytekConfig2.getApiSecret(), ts);
        // 创建请求
        Request request = new Request.Builder()
                .url(iflytekConfig2.getFileChunksUri() + "?fileId=" + fileId)
                .get()
                .addHeader("appId", iflytekConfig2.getAppId())
                .addHeader("timestamp", String.valueOf(ts))
                .addHeader("signature", signature)
                .build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            if (Objects.equals(response.code(), 200)) {
                String respBody = response.body().string();
                log.info("respBody: {}", respBody);
                JSONObject respJson = JSONObject.parseObject(respBody);
                return ResponseMsg.success(JSONUtil.toBean(respBody, ChunksResp.class), (String) respJson.get("desc"), (String) respJson.get("sid"));
            }
        } catch (IOException e) {
            log.error("fileChunks调用异常", e);
            throw new RuntimeException("文档分块内容获取，调用异常", e);
        }
        return null;
    }

    /**
     * 文档分块内容获取（供websocket调用）
     * 获取文件分块内容
     * GET，application/form-data
     *
     * @param fileId 上传的文件id
     * @return ChunksResp
     */
    public ChunksResp fileChunksWeb(String fileId) {
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .readTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .connectTimeout(20, TimeUnit.SECONDS)
                .build();

        long ts = System.currentTimeMillis() / 1000;

        String signature = ApiAuthUtil.getSignature(iflytekConfig2.getAppId(), iflytekConfig2.getApiSecret(), ts);
        // 创建请求
        Request request = new Request.Builder()
                .url(iflytekConfig2.getFileChunksUri() + "?fileId=" + fileId)
                .get()
                .addHeader("appId", iflytekConfig2.getAppId())
                .addHeader("timestamp", String.valueOf(ts))
                .addHeader("signature", signature)
                .build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            if (Objects.equals(response.code(), 200)) {
                String respBody = response.body().string();
                log.info("respBody: {}", respBody);
                return JSONUtil.toBean(respBody, ChunksResp.class);
            }
        } catch (IOException e) {
            log.error("fileChunks调用异常", e);
            throw new RuntimeException("文档分块内容获取，调用异常", e);
        }
        return null;
    }

    /**
     * 文档总结查询
     * 获取文档总结内容
     * POST，application/form-data
     *
     * @param fileId 上传的文件id
     * @return FileSummaryQueryResp
     */
    public ResponseMsg fileSummaryQuery(String fileId) {
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .readTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .connectTimeout(20, TimeUnit.SECONDS)
                .build();

        long ts = System.currentTimeMillis() / 1000;
        // 创建一个FormBody.Builder对象
        FormBody.Builder formBuilder = new FormBody.Builder();

        // 添加POST参数
        formBuilder.add("fileId", fileId);

        // 创建一个RequestBody对象，用于包装表单数据
        RequestBody requestBody = formBuilder.build();

        String signature = ApiAuthUtil.getSignature(iflytekConfig2.getAppId(), iflytekConfig2.getApiSecret(), ts);
        // 创建请求
        Request request = new Request.Builder()
                .url(iflytekConfig2.getFileSummaryQueryUri())
                .post(requestBody)
                .addHeader("appId", iflytekConfig2.getAppId())
                .addHeader("timestamp", String.valueOf(ts))
                .addHeader("signature", signature)
                .build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            if (Objects.equals(response.code(), 200)) {
                String respBody = response.body().string();
                log.info("respBody: {}", respBody);
                JSONObject respJson = JSONObject.parseObject(respBody);
                return ResponseMsg.success(JSONUtil.toBean(respBody, FileSummaryQueryResp.class), (String) respJson.get("desc"), (String) respJson.get("sid"));
            }
        } catch (IOException e) {
            log.error("调用异常", e);
            throw new RuntimeException("调用异常", e);
        }
        return null;
    }

    /**
     * 文档总结发起
     * 发起文档内容概要总结。
     * 只有 splited、vectoring、vectored 状态的文档才可以发起总结。文档状态可参考【1.文件管理 - 文档状态查询】
     * POST，application/form-data
     *
     * @param fileId 上传的文件id
     * @return String
     */
    public ResponseMsg fileSummaryStart(String fileId) {
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .readTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .connectTimeout(20, TimeUnit.SECONDS)
                .build();

        long ts = System.currentTimeMillis() / 1000;
        // 创建一个FormBody.Builder对象
        FormBody.Builder formBuilder = new FormBody.Builder();

        // 添加POST参数
        formBuilder.add("fileId", fileId);

        // 创建一个RequestBody对象，用于包装表单数据
        RequestBody requestBody = formBuilder.build();

        String signature = ApiAuthUtil.getSignature(iflytekConfig2.getAppId(), iflytekConfig2.getApiSecret(), ts);
        // 创建请求
        Request request = new Request.Builder()
                .url(iflytekConfig2.getFileSummaryStartUri())
                .post(requestBody)
                .addHeader("appId", iflytekConfig2.getAppId())
                .addHeader("timestamp", String.valueOf(ts))
                .addHeader("signature", signature)
                .build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            if (Objects.equals(response.code(), 200)) {
                String respBody = response.body().string();
                log.info("respBody: {}", respBody);
                JSONObject respJson = JSONObject.parseObject(respBody);
                return ResponseMsg.success(respJson.get("data"), (String) respJson.get("desc"), (String) respJson.get("sid"));
            }
        } catch (IOException e) {
            log.error("调用异常", e);
            throw new RuntimeException("调用异常", e);
        }
        return null;
    }

    /**
     * 文档详情
     * 查询文件详情。
     * POST，application/form-data
     *
     * @param fileId 上传的文件id
     * @return FileInfoResp
     */
    public ResponseMsg fileInfo(String fileId) {
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .readTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .connectTimeout(20, TimeUnit.SECONDS)
                .build();

        long ts = System.currentTimeMillis() / 1000;
        // 创建一个FormBody.Builder对象
        FormBody.Builder formBuilder = new FormBody.Builder();

        // 添加POST参数
        formBuilder.add("fileId", fileId);

        // 创建一个RequestBody对象，用于包装表单数据
        RequestBody requestBody = formBuilder.build();

        String signature = ApiAuthUtil.getSignature(iflytekConfig2.getAppId(), iflytekConfig2.getApiSecret(), ts);
        // 创建请求
        Request request = new Request.Builder()
                .url(iflytekConfig2.getFileInfoUri())
                .post(requestBody)
                .addHeader("appId", iflytekConfig2.getAppId())
                .addHeader("timestamp", String.valueOf(ts))
                .addHeader("signature", signature)
                .build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            if (Objects.equals(response.code(), 200)) {
                String respBody = response.body().string();
                log.info("respBody: {}", respBody);
                JSONObject respJson = JSONObject.parseObject(respBody);
                return ResponseMsg.success(JSONUtil.toBean(respBody, FileInfoResp.class), (String) respJson.get("desc"), (String) respJson.get("sid"));
            }
        } catch (IOException e) {
            log.error("调用异常", e);
            throw new RuntimeException("调用异常", e);
        }
        return null;
    }

    /**
     * 文档详情(供websocket调用)
     * 查询文件详情。
     * POST，application/form-data
     *
     * @param fileId 上传的文件id
     * @return FileInfoResp
     */
    public FileInfoResp fileInfoWeb(String fileId) {
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .readTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .connectTimeout(20, TimeUnit.SECONDS)
                .build();

        long ts = System.currentTimeMillis() / 1000;
        // 创建一个FormBody.Builder对象
        FormBody.Builder formBuilder = new FormBody.Builder();

        // 添加POST参数
        formBuilder.add("fileId", fileId);

        // 创建一个RequestBody对象，用于包装表单数据
        RequestBody requestBody = formBuilder.build();

        String signature = ApiAuthUtil.getSignature(iflytekConfig2.getAppId(), iflytekConfig2.getApiSecret(), ts);
        // 创建请求
        Request request = new Request.Builder()
                .url(iflytekConfig2.getFileInfoUri())
                .post(requestBody)
                .addHeader("appId", iflytekConfig2.getAppId())
                .addHeader("timestamp", String.valueOf(ts))
                .addHeader("signature", signature)
                .build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            if (Objects.equals(response.code(), 200)) {
                String respBody = response.body().string();
                log.info("respBody: {}", respBody);
                return JSONUtil.toBean(respBody, FileInfoResp.class);
            }
        } catch (IOException e) {
            log.error("调用异常", e);
            throw new RuntimeException("调用异常", e);
        }
        return null;
    }

    /**
     * 文档列表
     * 查询appId下的文件列表
     * POST，application/json
     *
     * @param fileListParam FileListParam
     * @return FileListResp
     */
    public ResponseMsg fileList(FileListParam fileListParam) {
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .readTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .connectTimeout(20, TimeUnit.SECONDS)
                .build();

        long ts = System.currentTimeMillis() / 1000;

        String json = JSONUtil.toJsonStr(fileListParam);
        RequestBody requestBody = RequestBody.Companion.create(MediaType.parse("application/json"), json);

        String signature = ApiAuthUtil.getSignature(iflytekConfig2.getAppId(), iflytekConfig2.getApiSecret(), ts);
        // 创建请求
        Request request = new Request.Builder()
                .url(iflytekConfig2.getFileListUri())
                .post(requestBody)
                .addHeader("appId", iflytekConfig2.getAppId())
                .addHeader("timestamp", String.valueOf(ts))
                .addHeader("signature", signature)
                .build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            if (Objects.equals(response.code(), 200)) {
                String respBody = response.body().string();
                log.info("respBody: {}", respBody);
                JSONObject respJson = JSONObject.parseObject(respBody);
                return ResponseMsg.success(JSONUtil.toBean(respBody, FileListResp.class), (String) respJson.get("desc"), (String) respJson.get("sid"));
            }
        } catch (IOException e) {
            log.error("调用异常", e);
            throw new RuntimeException("调用异常", e);
        }
        return null;
    }

    /**
     * 文档删除
     * 删除文档，该操作会删除文件向量等相关信息。
     * POST，application/form-data
     *
     * @param fileIds 上传的文件id列表，多个文档id用英文逗号分割
     * @return String
     */
    public ResponseMsg fileDel(String fileIds) {
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .readTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .connectTimeout(20, TimeUnit.SECONDS)
                .build();

        long ts = System.currentTimeMillis() / 1000;
        // 创建一个FormBody.Builder对象
        FormBody.Builder formBuilder = new FormBody.Builder();

        // 添加POST参数
        formBuilder.add("fileIds", fileIds);

        // 创建一个RequestBody对象，用于包装表单数据
        RequestBody requestBody = formBuilder.build();

        String signature = ApiAuthUtil.getSignature(iflytekConfig2.getAppId(), iflytekConfig2.getApiSecret(), ts);
        // 创建请求
        Request request = new Request.Builder()
                .url(iflytekConfig2.getFileDelUri())
                .post(requestBody)
                .addHeader("appId", iflytekConfig2.getAppId())
                .addHeader("timestamp", String.valueOf(ts))
                .addHeader("signature", signature)
                .build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            if (Objects.equals(response.code(), 200)) {
                String respBody = response.body().string();
                log.info("respBody: {}", respBody);
                JSONObject respJson = JSONObject.parseObject(respBody);
                return ResponseMsg.success(respJson.get("data"), (String) respJson.get("desc"), (String) respJson.get("sid"));
            }
        } catch (IOException e) {
            log.error("调用异常", e);
            throw new RuntimeException("调用异常", e);
        }
        return null;
    }

    /**
     * ########知识库管理模块相关接口 #########
     */
    /**
     * 知识库创建
     * 创建一个新的知识库。
     * POST，application/json
     *
     * @param repoCreateParam RepoCreateParam 创建知识库的请求体
     * @return String 知识库id，后续知识库操作使用
     */
    public ResponseMsg repoCreate(RepoCreateParam repoCreateParam) {
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .readTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .connectTimeout(20, TimeUnit.SECONDS)
                .build();

        long ts = System.currentTimeMillis() / 1000;

        String json = JSONUtil.toJsonStr(repoCreateParam);
        RequestBody requestBody = RequestBody.Companion.create(MediaType.parse("application/json"), json);

        String signature = ApiAuthUtil.getSignature(iflytekConfig2.getAppId(), iflytekConfig2.getApiSecret(), ts);
        // 创建请求
        Request request = new Request.Builder()
                .url(iflytekConfig2.getRepoCreateUri())
                .post(requestBody)
                .addHeader("appId", iflytekConfig2.getAppId())
                .addHeader("timestamp", String.valueOf(ts))
                .addHeader("signature", signature)
                .build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            if (Objects.equals(response.code(), 200)) {
                String respBody = response.body().string();
                log.info("respBody: {}", respBody);
                JSONObject respJson = JSONObject.parseObject(respBody);
                return ResponseMsg.success(respJson.get("data"), (String) respJson.get("desc"), (String) respJson.get("sid"));
            }
        } catch (IOException e) {
            log.error("调用异常", e);
            throw new RuntimeException("调用异常", e);
        }
        return null;
    }

    /**
     * 添加文件
     * 向知识库中添加文件，每次操作最多可添加20个文件进知识库，文件较多时，需要分多次添加。且同一个文件最多可存在于10个不同知识库。
     * 注：仅文档状态为vectored的文件才可以进行问答，文档状态可参考【1.文件管理 - 文档状态查询】
     * POST，application/json
     *
     * @param repoFileParam RepoFileParam
     * @return RepoFileAddResp
     */
    public ResponseMsg repoFileAdd(RepoFileParam repoFileParam) {
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .readTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .connectTimeout(20, TimeUnit.SECONDS)
                .build();

        long ts = System.currentTimeMillis() / 1000;

        String json = JSONUtil.toJsonStr(repoFileParam);
        RequestBody requestBody = RequestBody.Companion.create(MediaType.parse("application/json"), json);

        String signature = ApiAuthUtil.getSignature(iflytekConfig2.getAppId(), iflytekConfig2.getApiSecret(), ts);
        // 创建请求
        Request request = new Request.Builder()
                .url(iflytekConfig2.getRepoFileAddUri())
                .post(requestBody)
                .addHeader("appId", iflytekConfig2.getAppId())
                .addHeader("timestamp", String.valueOf(ts))
                .addHeader("signature", signature)
                .build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            if (Objects.equals(response.code(), 200)) {
                String respBody = response.body().string();
                log.info("respBody: {}", respBody);
                JSONObject respJson = JSONObject.parseObject(respBody);
                return ResponseMsg.success(JSONUtil.toBean(respBody, RepoFileAddResp.class), (String) respJson.get("desc"), (String) respJson.get("sid"));
            }
        } catch (IOException e) {
            log.error("调用异常", e);
            throw new RuntimeException("调用异常", e);
        }
        return null;
    }

    /**
     * 移除文件
     * 从知识库中移除文件，一次最多操作20个文件。
     * POST，application/json
     *
     * @param repoFileParam RepoFileParam
     * @return RepoFileAddResp
     */
    public ResponseMsg repoFileRemove(RepoFileParam repoFileParam) {
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .readTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .connectTimeout(20, TimeUnit.SECONDS)
                .build();

        long ts = System.currentTimeMillis() / 1000;

        String json = JSONUtil.toJsonStr(repoFileParam);
        RequestBody requestBody = RequestBody.Companion.create(MediaType.parse("application/json"), json);

        String signature = ApiAuthUtil.getSignature(iflytekConfig2.getAppId(), iflytekConfig2.getApiSecret(), ts);
        // 创建请求
        Request request = new Request.Builder()
                .url(iflytekConfig2.getRepoFileRemoveUri())
                .post(requestBody)
                .addHeader("appId", iflytekConfig2.getAppId())
                .addHeader("timestamp", String.valueOf(ts))
                .addHeader("signature", signature)
                .build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            if (Objects.equals(response.code(), 200)) {
                String respBody = response.body().string();
                log.info("respBody: {}", respBody);
                JSONObject respJson = JSONObject.parseObject(respBody);
                return ResponseMsg.success(JSONUtil.toBean(respBody, RepoFileAddResp.class), (String) respJson.get("desc"), (String) respJson.get("sid"));
            }
        } catch (IOException e) {
            log.error("调用异常", e);
            throw new RuntimeException("调用异常", e);
        }
        return null;
    }

    /**
     * 知识库列表
     * 查询app下知识库列表
     * POST，application/json
     *
     * @param repoListParam RepoListParam
     * @return RepoListResp
     */
    public ResponseMsg repoList(RepoListParam repoListParam) {
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .readTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .connectTimeout(20, TimeUnit.SECONDS)
                .build();

        long ts = System.currentTimeMillis() / 1000;

        String json = JSONUtil.toJsonStr(repoListParam);
        RequestBody requestBody = RequestBody.Companion.create(MediaType.parse("application/json"), json);

        String signature = ApiAuthUtil.getSignature(iflytekConfig2.getAppId(), iflytekConfig2.getApiSecret(), ts);
        // 创建请求
        Request request = new Request.Builder()
                .url(iflytekConfig2.getRepoListUri())
                .post(requestBody)
                .addHeader("appId", iflytekConfig2.getAppId())
                .addHeader("timestamp", String.valueOf(ts))
                .addHeader("signature", signature)
                .build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            if (Objects.equals(response.code(), 200)) {
                String respBody = response.body().string();
                log.info("respBody: {}", respBody);
                JSONObject respJson = JSONObject.parseObject(respBody);
                return ResponseMsg.success(JSONUtil.toBean(respBody, RepoListResp.class), (String) respJson.get("desc"), (String) respJson.get("sid"));
            }
        } catch (IOException e) {
            log.error("调用异常", e);
            throw new RuntimeException("调用异常", e);
        }
        return null;
    }

    /**
     * 知识库详情
     * 查询知识库详情
     * POST，application/form-data
     *
     * @param repoId 知识库ID
     * @return RepoInfoResp
     */
    public ResponseMsg repoInfo(String repoId) {
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .readTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .connectTimeout(20, TimeUnit.SECONDS)
                .build();

        long ts = System.currentTimeMillis() / 1000;
        // 创建一个FormBody.Builder对象
        FormBody.Builder formBuilder = new FormBody.Builder();

        // 添加POST参数
        formBuilder.add("repoId", repoId);

        // 创建一个RequestBody对象，用于包装表单数据
        RequestBody requestBody = formBuilder.build();

        String signature = ApiAuthUtil.getSignature(iflytekConfig2.getAppId(), iflytekConfig2.getApiSecret(), ts);
        // 创建请求
        Request request = new Request.Builder()
                .url(iflytekConfig2.getRepoInfoUri())
                .post(requestBody)
                .addHeader("appId", iflytekConfig2.getAppId())
                .addHeader("timestamp", String.valueOf(ts))
                .addHeader("signature", signature)
                .build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            if (Objects.equals(response.code(), 200)) {
                String respBody = response.body().string();
                log.info("respBody: {}", respBody);
                JSONObject respJson = JSONObject.parseObject(respBody);
                return ResponseMsg.success(JSONUtil.toBean(respBody, RepoInfoResp.class), (String) respJson.get("desc"));
            }
        } catch (IOException e) {
            log.error("调用异常", e);
            throw new RuntimeException("调用异常", e);
        }
        return null;
    }

    /**
     * 知识库文件列表
     * 查询知识库下所有文件
     * POST，application/json
     *
     * @param repoFileListParam RepoFileListParam
     * @return RepoFileListResp
     */
    public ResponseMsg repoFileList(RepoFileListParam repoFileListParam) {
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .readTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .connectTimeout(20, TimeUnit.SECONDS)
                .build();

        long ts = System.currentTimeMillis() / 1000;

        String json = JSONUtil.toJsonStr(repoFileListParam);
        RequestBody requestBody = RequestBody.Companion.create(MediaType.parse("application/json"), json);

        String signature = ApiAuthUtil.getSignature(iflytekConfig2.getAppId(), iflytekConfig2.getApiSecret(), ts);
        // 创建请求
        Request request = new Request.Builder()
                .url(iflytekConfig2.getRepoFileListUri())
                .post(requestBody)
                .addHeader("appId", iflytekConfig2.getAppId())
                .addHeader("timestamp", String.valueOf(ts))
                .addHeader("signature", signature)
                .build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            if (Objects.equals(response.code(), 200)) {
                String respBody = response.body().string();
                log.info("respBody: {}", respBody);
                JSONObject respJson = JSONObject.parseObject(respBody);
                return ResponseMsg.success(JSONUtil.toBean(respBody, RepoFileListResp.class), (String) respJson.get("desc"), (String) respJson.get("sid"));
            }
        } catch (IOException e) {
            log.error("调用异常", e);
            throw new RuntimeException("调用异常", e);
        }
        return null;
    }

    /**
     * 知识库删除
     * 删除知识库
     * POST，application/form-data
     *
     * @param repoId 知识库ID
     * @return String
     */
    public ResponseMsg repoDel(String repoId) {
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .readTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .connectTimeout(20, TimeUnit.SECONDS)
                .build();

        long ts = System.currentTimeMillis() / 1000;
        // 创建一个FormBody.Builder对象
        FormBody.Builder formBuilder = new FormBody.Builder();

        // 添加POST参数
        formBuilder.add("repoId", repoId);

        // 创建一个RequestBody对象，用于包装表单数据
        RequestBody requestBody = formBuilder.build();

        String signature = ApiAuthUtil.getSignature(iflytekConfig2.getAppId(), iflytekConfig2.getApiSecret(), ts);
        // 创建请求
        Request request = new Request.Builder()
                .url(iflytekConfig2.getRepoDelUri())
                .post(requestBody)
                .addHeader("appId", iflytekConfig2.getAppId())
                .addHeader("timestamp", String.valueOf(ts))
                .addHeader("signature", signature)
                .build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            if (Objects.equals(response.code(), 200)) {
                String respBody = response.body().string();
                log.info("respBody: {}", respBody);
                JSONObject respJson = JSONObject.parseObject(respBody);
                return ResponseMsg.success(respJson.get("data"), (String) respJson.get("desc"), (String) respJson.get("sid"));
            }
        } catch (IOException e) {
            log.error("调用异常", e);
            throw new RuntimeException("调用异常", e);
        }
        return null;
    }

}
